﻿using System;
using System.IO;
using System.IO.Pipes;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;

namespace AutoUpdateTool.Controller
{
    public class FileController : ApiController
    {
        /// <summary>
        /// 从WebAPI下载文件
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage Get(string dir)
        {
            try
            {
                string filePath = Path.Combine(Common.FilesRootPath, dir.TrimStart('/'));
                // 检查文件是否存在
                if (!File.Exists(filePath))
                    return Request.CreateErrorResponse(HttpStatusCode.NotFound, "文件不存在");

                // 读取文件
                FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                // 将文件流复制到响应流中
                response.Content = new StreamContent(fileStream);
                // 设置响应内容类型
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                // 设置响应头，指定文件名
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = HttpUtility.UrlEncode(Path.GetFileName(filePath))
                };
                // 设置响应头，指定文件大小
                response.Content.Headers.ContentLength = fileStream.Length;
                return response;
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex.Message);
            }
        }
    }
}
